package com.bw.a2209clubshop.ui.login.viewModel

import android.util.Log
import androidx.lifecycle.viewModelScope
import com.bawei.a2209_mianshi.utils.GSON
import com.bw.a2209clubshop.appContext
import com.bw.a2209clubshop.base.BaseViewModel
import com.bw.a2209clubshop.base.state.Failed
import com.bw.a2209clubshop.base.state.Loading
import com.bw.a2209clubshop.base.state.RequestEvent
import com.bw.a2209clubshop.base.state.Success
import com.bw.a2209clubshop.mmkv.AuthMMKV
import com.bw.a2209clubshop.ui.login.model.LoginMode
import com.bw.a2209clubshop.ui.login.model.LoginResult
import com.bw.a2209clubshop.ui.login.repository.LoginRepository
import com.bw.a2209clubshop.utils.MD5
import com.bw.a2209clubshop.utils.ToastUtils
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class LoginViewModel@Inject constructor(
    private val mRepository: LoginRepository
):BaseViewModel(){
    //保存当前正在显示的fragment
    private val _currentFragment = MutableStateFlow("")
    val currentFragment: StateFlow<String>
        get() = _currentFragment

    val phone: MutableStateFlow<String> = MutableStateFlow("")
    val password: MutableStateFlow<String> = MutableStateFlow("")

    val restPassword: MutableStateFlow<String> = MutableStateFlow("")
    val confirmPassword: MutableStateFlow<String> = MutableStateFlow("")

    fun clearRestPassword() {
        restPassword.value = ""

    }

    fun clearConfirmPassword() {
        confirmPassword.value = ""
    }

    fun clearPhone() {
        phone.value = ""
    }

    fun clearPassword() {
        password.value = ""
    }


    //channel 适合一对一，非粘性，可避免shareFlow订阅时间晚,丢失第一条信息的问题
    private val _requestSmsCodeEvent = Channel<RequestEvent>()
    val requestSmsCodeEvent get() = _requestSmsCodeEvent.receiveAsFlow()

    //登录请求事件
    private val _requestLoginEvent = MutableSharedFlow<RequestEvent>()
    val requestLoginEvent get() = _requestLoginEvent.asSharedFlow()

    //校验验证码事件
    private val _checkSmsCodeEvent = MutableSharedFlow<RequestEvent>()
    val mCheckSmsCodeEvent get() = _checkSmsCodeEvent.asSharedFlow()

    var requestRest: Boolean = false

    //请求发送验证码的时间
    var sendSmsCodeTimeStamp: Long = 0L
    fun setShowingFragmentTag(tag: String) {
        _currentFragment.value = tag
    }

    var wxCode: String = ""
    var wxOpenId: String = ""

    //微信用户信息
    var gender = 0
    var nickName: String = ""
    var headImg = ""


    fun resetSmsCodeEvent(success: Boolean) {
        viewModelScope.launch {
            _requestSmsCodeEvent.send(if (success) Success else Failed(""))
        }
    }

    //获取短信验证码
    fun getSmsCode(type: String) {
        execute(
            action = mRepository.getLoginSmsCode(phone.value),
//            if (type == "login")
//                mRepository.getLoginSmsCode(phone.value)
//            else if (type == "rest") {
////                mRepository.getRestSmsCode(phone.value)
//            } else {
////                mRepository.getBindSmsCode(phone.value)
//            },
            onStart = {
                _requestSmsCodeEvent.send(Loading)
            },
            onError = {
                _requestSmsCodeEvent.send(Failed(it))
            },
            onFinish = {
                ToastUtils.showLong(appContext,it.msg)
                _requestSmsCodeEvent.send(Success)
            })
    }
    //验证码登录
    fun loginBySmsCode(smsCode: String) {
        viewModelScope.launch {
            _requestLoginEvent.emit(Loading)
            mRepository.login(LoginMode.SMS, phone.value, smsCode)
                .collect {
                    if (it.data == null) {
                        _requestLoginEvent.emit(Failed(it.msg))
                        return@collect
                    }
                    //保存token
                    val result=GSON.toJson(it.data) as LoginResult
                    AuthMMKV.token = result.access_token
                    //获取用户信息
                    ToastUtils.showLong(appContext,it.msg)
//                    getUserInfo()
                }
        }
    }
    //账号密码登录
    fun loginByAccount() {
        execute(
            action = mRepository.login(LoginMode.PASSWORD, phone.value, MD5.toMD5(password.value)),
            onStart = {
                _requestLoginEvent.emit(Loading)
            },
            onError = {
                _requestLoginEvent.emit(Failed(it))
            },
            onFinish = {
                //保存token
                AuthMMKV.token = (it.data as Map<*, *>)["access_token"] as String
                //请求用户信息
                ToastUtils.showLong(appContext,it.msg)
//                getUserInfo()
                //_requestLoginEvent.emit(Success)
            }
        )
    }
}